﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Hematology.Data;
using Hematology.Tools;
using Hematology.UserSite.Controls;
using NgoResource = Hematology.UserSite.App_GlobalResources.UserSite;

namespace Hematology.UserSite.admin
{
	public partial class RoleManagement : NgoPage
	{
		#region Fields

		private const string ListUrl = "/admin/RoleManagement.aspx?view=List";

		#endregion

		#region Properties

		private EnumHelper.PageSection CurrentPageSection
		{
			get
			{
				return ViewState["CurrentPageSection"] != null
						   ? (EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), ViewState["CurrentPageSection"].ToString())
						   : EnumHelper.PageSection.List;
			}
			set { ViewState["CurrentPageSection"] = value; }
		}

		private AccessRole CurrentAccessRole
		{
			get { return (AccessRole)ViewState["CurrentAccessRole"]; }
			set { ViewState["CurrentAccessRole"] = value; }
		}

		#endregion

		#region Fill methods

		private void FillViewStateVariables()
		{
			string pageSection = Request.QueryString["view"];
			if (Array.IndexOf(Enum.GetNames(typeof(EnumHelper.PageSection)), pageSection) > -1)
			{
				CurrentPageSection =
					(EnumHelper.PageSection)Enum.Parse(typeof(EnumHelper.PageSection), pageSection);
			}
		}

		private void FillEditForm()
		{
			string sRoleId = Request.QueryString["id"];
			int iRoleId;
			if (!String.IsNullOrEmpty(sRoleId) && Int32.TryParse(sRoleId, out iRoleId))
			{
				AccessRole accessRole = AccessRole.Get(iRoleId);
				if (accessRole != null)
				{
					CurrentAccessRole = accessRole;

					txtRoleName.Text = accessRole.Name;
					txtRoleDescription.Text = accessRole.Description;
				}
			}
		}

		private void FillPage()
		{
			switch (CurrentPageSection)
			{
				case EnumHelper.PageSection.Edit:
				case EnumHelper.PageSection.Add:
					mvRoles.ActiveViewIndex = 1;
					FillEditForm();

					break;
				default:
					mvRoles.ActiveViewIndex = 0;
					FillRoleList();

					break;
			}
		}

		private void FillRoleList()
		{
			List<AccessRole> lAccessRole = AccessRole.GetAllRoles();

			foreach (AccessRole accessRole in lAccessRole)
			{
				if (String.IsNullOrEmpty(accessRole.Description))
					accessRole.Description = NgoResource.resWhitespace;
			}

			rptAccessRole.DataSource = lAccessRole;
			rptAccessRole.DataBind();
		}

		#endregion

		#region Event handlers

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				FillViewStateVariables();
				FillPage();
			}
		}

		protected void btnSaveRole_Click(object sender, EventArgs e)
		{
			string roleName = txtRoleName.Text.Trim();
			if (!String.IsNullOrEmpty(roleName))
			{
				AccessRole accessRole = AccessRole.SearchByName(roleName);

				if (CurrentPageSection == EnumHelper.PageSection.Add)
				{
					if (accessRole != null)
						throw new Exception("Роль с таким названием была создана раннее. Выберите другое название");

					AccessRole newAccessRole = new AccessRole
												   {
													   Name = roleName,
													   Description = txtRoleDescription.Text.Trim(),
												   };

					newAccessRole.Save();

					if (newAccessRole.RoleId != null)
						Response.Redirect(ListUrl);
				}

				if (CurrentPageSection == EnumHelper.PageSection.Edit)
				{
					if (accessRole != null && !roleName.Equals(CurrentAccessRole.Name))
						throw new Exception("Выбранное название принадлежит другой роли, созданной раннее. Выберите другое название");

					CurrentAccessRole.Name = roleName;
					CurrentAccessRole.Description = txtRoleDescription.Text.Trim();

					CurrentAccessRole.UpdateInstance();

					Response.Redirect(ListUrl);
				}
			}
		}

		protected void rptAccessRole_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "DeleteRole")
			{
				int roleId = Convert.ToInt32(e.CommandArgument);
				AccessRole accessRole = AccessRole.Get(roleId);
				accessRole.IsDeleted = true;

				accessRole.UpdateInstance();

				FillRoleList();
			}
		}

		protected void ptTitle_AddButtonClick(object sender, EventArgs e)
		{
			Response.Redirect("/admin/RoleManagement.aspx?view=Add");
		}

		protected void btnList_Click(object sender, EventArgs e)
		{
			Response.Redirect(ListUrl);
		}

		#endregion
	}
}